package com.rndemo.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.app.KeyguardManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Photo;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.MutableBoolean;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;


import com.rndemo.Environmental.AppConfig;
import com.rndemo.Environmental.AppData;
import com.rndemo.entity.Contacts;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class UtilSystem {
    /**
     * 判断网络是否连接
     */
    public static boolean isHaveNet(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.isConnected());
//		return info != null;// 网络是否连接
    }

    /**
     * 判断是否为wifi联网
     */
    public static boolean isWiFi(Context cxt) {
        ConnectivityManager cm = (ConnectivityManager) cxt.getSystemService(Context.CONNECTIVITY_SERVICE);
        // wifi的状态：ConnectivityManager.TYPE_WIFI
        // 3G的状态：ConnectivityManager.TYPE_MOBILE
        State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        return State.CONNECTED == state;
    }


    /**
     * 获取手机IMEI码
     */
    public static String getPhoneIMEI(Context ctx) {
        TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            throw new RuntimeException("请获取权限");
        }
        return tm.getDeviceId();
    }

    /**
     * 获取手机系统SDK版本
     *
     * @return 如API 17 则返回 17
     */
    public static int getSDKVersion() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取系统版本
     *
     * @return 形如2.3.3
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 调用系统发送短信
     */
    public static void sendSMS(Context cxt, String smsBody) {
        Uri smsToUri = Uri.parse("smsto:");
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", smsBody);
        cxt.startActivity(intent);
    }

    /**
     * 调用系统发送短信
     * <uses-permission android:name="android.permission.CALL_PHONE" />
     */
    public static void call(Context cxt, String number) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + number));
        cxt.startActivity(intent);
    }

    /**
     * 隐藏系统键盘
     */
    public static void hideKeyBoard(Activity act) {
        //这个是取反(存在则消息，不存在则出现)
//		((InputMethodManager) aty.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        //此方法好像不行用下面的
//		((InputMethodManager) aty.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(aty.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        View currentFocus = act.getCurrentFocus();
        if (currentFocus == null) {
            return;
        }
        ((InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(currentFocus.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    /**
     * 显示系统键盘
     */
    public static void showKeyBoard(Activity act, View v) {
        v.requestFocus();//得到焦点
        ((InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(v, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    /**
     * 有无相机
     *
     * @param context
     * @return
     * @return: boolean
     */
    public static boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断当前应用程序是否后台运行
     */
    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 后台运行
                    return true;
                } else {
                    // 前台运行
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 栈的前10个有没有指定的Activity(见意不要用)
     *
     * @param <T>
     * @return
     * @return: boolean
     */
    @SuppressWarnings("deprecation")
    public static <T extends Activity> boolean isBackAct(Context cxt, Class<T> c, int n) {
        //是否启动了主界面
        Intent intent = new Intent(cxt, c);
        ComponentName cmpName = intent.resolveActivity(cxt.getPackageManager());

        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> taskInfoList = am.getRunningTasks(n);

        for (RunningTaskInfo taskInfo : taskInfoList) {
            if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                return true;
            }
        }
        return false;
    }


    /**
     * 判断手机是否处于睡眠
     */
    public static boolean isSleeping(Context context) {
        KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
        return isSleeping;
    }

    /**
     * 安装apk
     *
     * @param context
     * @param file
     */
    public static void installApk(Context context, File file) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setType("application/vnd.android.package-archive");
            intent.setData(Uri.fromFile(file));
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 安装apk
     *
     * @param context
     * @param filePath
     * @return: void
     */
    public static void installApk(Context context, String filePath) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void unInstallApk(Context ctx, String packageName) {
        if (packageName == null) {
            packageName = ctx.getPackageName();
        }
        Uri packageURI = Uri.parse("package:" + packageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        ctx.startActivity(uninstallIntent);
    }

    /**
     * 静默安装要root权限
     *
     * @return -1无root权限
     * -2 管理root时没同意
     * 0成功安装
     **/
    public static int installApk(String pathName) {
        String cmd = "pm install -r " + pathName;
        return excuteSuCMD(cmd);
    }

    /**
     * 静默卸载要root权限
     *
     * @param packageName
     * @return -1无root权限
     * -2 管理root时没同意
     * 0成功卸载
     */
    public static int unInstallApk(String packageName) {
        String cmd = "pm uninstall -k " + packageName;
        return excuteSuCMD(cmd);
    }

    private static int excuteSuCMD(String cmd) {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream dos = new DataOutputStream(process.getOutputStream());
            // 部分手机Root之后Library path 丢失，导入path可解决该问题
            dos.writeBytes("export LD_LIBRARY_PATH=/vendor/lib:/system/lib\n");
            cmd = String.valueOf(cmd);
            dos.writeBytes((cmd + "\n"));
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            process.waitFor();
            String s = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                s += line + "\n";
            }
            if (s.equals("")) {//用户root管理没同意
                return -2;
            }
            int result = process.exitValue();
            return result;//只要有root权限就是0
        } catch (Exception localException) {
            localException.printStackTrace();
            return -1;//没有root权限时
        }
    }

    /**
     * "am start -n " + packageName + "/" + activityName + " \n"//启动app
     */
    public static String exec(String cmd) {
        String s = "";
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                s += line + "\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return s;
    }

    /**
     * 得到当前进程名
     */
    public static String getProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 创建快捷方式
     */
    public void createDeskShortCut(Context cxt, Class<?> cls, int res, int nameRes) {
        // 创建快捷方式的Intent
        Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允许重复创建
        shortcutIntent.putExtra("duplicate", false);
        // 需要现实的名称
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, cxt.getString(nameRes));
        // 快捷图片
        Parcelable icon = Intent.ShortcutIconResource.fromContext(cxt.getApplicationContext(), res);
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        Intent intent = new Intent(cxt, cls);
        // 下面两个属性是为了当应用程序卸载时桌面上的快捷方式会删除
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        // 点击快捷图片，运行的程序主入口
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        // 发送广播。OK
        cxt.sendBroadcast(shortcutIntent);
    }

    /**
     * 获取当前应用程序的版本号
     */
    public static String getAppVersion(Context context) {
        String version = "0";
        try {
            version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 回到home，后台运行
     */
    public static void goHome(Context context) {
        Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        context.startActivity(mHomeIntent);
    }

    /**
     * 获取应用签名
     *
     * @param context
     * @param pkgName
     */
    public static String getSign(Context context, String pkgName) {
        try {
            PackageInfo pis = context.getPackageManager().getPackageInfo(pkgName, PackageManager.GET_SIGNATURES);
            return hexdigest(pis.signatures[0].toByteArray());
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否为模拟器
     */
    public static boolean isEmulator(Context ctx) {
        try {
            String imei = getPhoneIMEI(ctx);
            //000000000000000  要是不带电话功能的机子怎么办
            return imei.startsWith("000") || (Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"));
        } catch (Exception ioe) {
        }
        return false;
    }
//	public static boolean isEmulator(Context context) {
//		String result = "";
//		try {
//			String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
//			ProcessBuilder cmd = new ProcessBuilder(args);
//
//			Process process = cmd.start();
//			StringBuffer sb = new StringBuffer();
//			String readLine = "";
//			BufferedReader responseReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
//			while ((readLine = responseReader.readLine()) != null) {
//				sb.append(readLine);
//			}
//			responseReader.close();
//			result = sb.toString().toLowerCase();
//		} catch (IOException ex) {
//		}
//		return (!result.contains("arm")) || (result.contains("intel")) || (result.contains("amd"));
//	}


    /**
     * 将签名字符串转换成需要的32位签名
     */
    private static String hexdigest(byte[] paramArrayOfByte) {
        final char[] hexDigits = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102};
        try {
            MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
            localMessageDigest.update(paramArrayOfByte);
            byte[] arrayOfByte = localMessageDigest.digest();
            char[] arrayOfChar = new char[32];
            for (int i = 0, j = 0; ; i++, j++) {
                if (i >= 16) {
                    return new String(arrayOfChar);
                }
                int k = arrayOfByte[i];
                arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
                arrayOfChar[++j] = hexDigits[(k & 0xF)];
            }
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 获取设备的可用内存大小
     *
     * @param cxt 应用上下文对象context
     * @return 当前内存大小
     */
    public static int getDeviceUsableMemory(Context cxt) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);
        // 返回当前系统的可用内存
        return (int) (mi.availMem / (1024 * 1024));
    }

    /**
     * 退出
     * <p>注意    <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
     *
     * @param context
     * @return: void
     */
    public static void exitSys(Context context) {
        ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activityMgr.killBackgroundProcesses(context.getPackageName());
        System.exit(0);
    }

    /**
     * 退出
     * <p>注意    <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
     *
     * @return: void
     */
    public static void exitSys() {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }


    /**
     * 清理后台进程与服务(不含自身)
     *
     * @param cxt 应用上下文对象context
     * @return 被清理的数量
     */
    public static int gc(Context cxt) {
        long i = getDeviceUsableMemory(cxt);
        int count = 0; // 清理掉的进程数
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        // 获取正在运行的service列表
        List<RunningServiceInfo> serviceList = am.getRunningServices(100);
        if (serviceList != null)
            for (RunningServiceInfo service : serviceList) {
                if (service.pid == android.os.Process.myPid())
                    continue;
                try {
                    android.os.Process.killProcess(service.pid);
                    count++;
                } catch (Exception e) {
                    e.getStackTrace();
                    continue;
                }
            }

        // 获取正在运行的进程列表
        List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
        if (processList != null)
            for (RunningAppProcessInfo process : processList) {
                // 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE的进程都长时间没用或者空进程了
                // 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE的进程都是非可见进程，也就是在后台运行着
                if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                    // pkgList 得到该进程下运行的包名
                    String[] pkgList = process.pkgList;
                    for (String pkgName : pkgList) {
                        System.out.println("======正在杀死包名：" + pkgName);
                        try {
                            am.killBackgroundProcesses(pkgName);
                            count++;
                        } catch (Exception e) { // 防止意外发生
                            e.getStackTrace();
                            continue;
                        }
                    }
                }
            }
        System.out.println("清理了" + (getDeviceUsableMemory(cxt) - i) + "M内存");
        return count;
    }


    /**
     * 下载
     * <p>
     * UtilSystem.downLoad(
     * "http://www.baidu.com/img/bdlogo.png",
     * "xiaoniu/download",
     * "bdlog.png",
     * "图片");
     *
     * @param url
     * @param name  文件名
     * @param title 通知显示的标题
     * @return
     * @return: long
     */
    public static long downLoad(String url,String name, int visibility, String title) {
        DownloadManager download = (DownloadManager) AppData.mAppCxt.getSystemService(Context.DOWNLOAD_SERVICE);

        Request request = new Request(Uri.parse(url));
        // 设置允许使用的网络类型，这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(true);
        // 设置文件类型
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        request.setMimeType(mimeString);

        // 禁止发出通知，既后台下载，如果要使用这一句必须声明一个权限：android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
//		request.setShowRunningNotification(notif);
        request.setNotificationVisibility(visibility);

        // 不显示下载界面
        request.setVisibleInDownloadsUi(true);

//        UtilFile.isHaveFile(path);
//        path = path.replace(sdPath, "");
        // sdcard的目录下的download文件夹   "android.permission.WRITE_EXTERNAL_STORAGE"
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name);

        request.setTitle(title);
        //将下载请求放入队列
        return download.enqueue(request);
    }

    public static long downLoad(String url, String name, String title) {
        return downLoad(url, name, Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED, title);
    }

    public static long downLoad(String url, String name) {
        return downLoad(url, name, Request.VISIBILITY_HIDDEN, null);
    }

    /**
     * 获取本地机器IP
     * <uses-permission android:name="android.permission.INTERNET" >
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String value = inetAddress.getHostAddress();
                        if (value.contains("."))
                            return value;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 得到ip
     */
    public static String intToIp(Context ctx) {
        WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        int i = wifiManager.getConnectionInfo().getIpAddress();
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
    }

    /**
     * 取得AppKey
     *
     * @param context
     * @return
     * @return: String
     */
    public static String getAppKey(Context context, String kayName) {
        Bundle metaData = null;
        String appKey = null;
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai)
                metaData = ai.metaData;
            if (null != metaData) {
                appKey = metaData.getString(kayName);
                if ((null == appKey) || appKey.length() < 6) {//大于6位
                    appKey = null;
                }
            }
        } catch (NameNotFoundException e) {

        }
        return appKey;
    }

    /**
     * 屏幕是否亮着
     */
    public static boolean isScreenOn(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            return pm.isInteractive();
        }
        return pm.isScreenOn();
    }

    /**
     * 获得当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    public static int getScreenMode(Context ctx) {
        int screenMode = -1;
        try {
            screenMode = Settings.System.getInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenMode;
    }

    /**
     * 设置当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    public static void setScreenMode(Context ctx, int paramInt) {
        try {
            Settings.System.putInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, paramInt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置电源状态
     * <uses-permission android:name="android.permission.WAKE_LOCK"/>
     * cpu       screen       keyboard
     * PARTIAL_WAKE_LOCK                on         off           off
     * SCREEN_DIM_WAKE_LOCK         	on         dim           off
     * SCREEN_BRIGHT_WAKE_LOCK   		on         bright        off
     * FULL_WAKE_LOCK                   on         bright        bright
     */
    public static void setScreenLight(Context ctx, boolean isLight, int flag) {
        PowerManager manager = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        WakeLock newWakeLock = manager.newWakeLock(flag, "May Video Tag");
        if (isLight) {
            newWakeLock.acquire();//保持
        } else {
            newWakeLock.release();//释放
        }
    }

    /**
     * 获得当前屏幕亮度值  0--255
     *
     * @return -1 出错
     */
    public static int getScreenBrightness(Context ctx) {
        int screenBrightness = -1;
        try {
            screenBrightness = Settings.System.getInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenBrightness;
    }

    /**
     * 设置当前屏幕亮度值  0--255
     */
    public static void setScreenBrightness(Activity act, int paramInt) {
        paramInt = paramInt < 5 ? 5 : paramInt;
        paramInt = paramInt > 255 ? 250 : paramInt;
        try {
            Settings.System.putInt(act.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, paramInt);
            Window localWindow = act.getWindow();
            WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
            localLayoutParams.screenBrightness = paramInt;
            localWindow.setAttributes(localLayoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置声音大小 调一次声音改变一次
     *
     * @param ctx
     * @param add
     * @return: void
     */
    @SuppressWarnings("static-access")
    public static void setVolume(Context ctx, boolean add) {
        AudioManager audioManager = (AudioManager) ctx.getSystemService(Service.AUDIO_SERVICE);
        if (add) {
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        } else {
            audioManager.adjustStreamVolume(audioManager.STREAM_MUSIC, audioManager.ADJUST_LOWER, audioManager.FLAG_SHOW_UI);
        }
    }


    /**
     * 录音
     *
     * @param ctx
     * @param path
     * @param c
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static MutableBoolean recorde(Context ctx, String path, final IrecordeCallback c) {
        final MutableBoolean isRecording = new MutableBoolean(false);
        final MediaRecorder recorder = new MediaRecorder();
        final long startTime = System.currentTimeMillis();
        if (!path.endsWith(".amr")) {
            path += ".amr";
        }
        final File file = new File(path);
        try {
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setAudioChannels(1); // MONO
            recorder.setAudioSamplingRate(8000); // 8000Hz
            recorder.setAudioEncodingBitRate(64); // seems if change this to
            // 128, still got same file
            // size.
            recorder.setOutputFile(file.getAbsolutePath());
            recorder.prepare();
            isRecording.value = true;
            recorder.start();
        } catch (IOException e) {
            recorder.stop();
            recorder.release();
            file.deleteOnExit();
            c.err(e);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (isRecording.value) {
                        int what = recorder.getMaxAmplitude() * 13 / 0x7FFF;
                        c.recordeing(what);
                        SystemClock.sleep(100);
                    }
                    recorder.stop();
                    recorder.release();
                    file.deleteOnExit();
                    int time = (int) (System.currentTimeMillis() - startTime) / 1000;
                    c.stop(file.getAbsolutePath(), time);
                } catch (Exception e) {
                    recorder.stop();
                    recorder.release();
                    file.deleteOnExit();
                    c.err(e);
                }
            }
        }).start();
        return isRecording;
    }


    /**
     * 录音的回调接口
     */
    public interface IrecordeCallback {
        void err(Exception e);

        /**
         * @param i 振幅
         */
        void recordeing(int i);

        /**
         * @param path 文件路径
         * @param time 文件时长
         */
        void stop(String path, int time);
    }

    /**
     * 获取库Phon表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID};
    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;
    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;
    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;

    /**
     * 得到手机SIM卡联系人人信息
     **/
    public static List<Contacts> getPhoneContacts(Context ctx) {
        List<Contacts> list = new ArrayList<>();
        ContentResolver resolver = ctx.getContentResolver();
        // 得到手机SIM卡联系人人信息
        Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                // 得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
                // 得到联系人头像ID
                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
                // 得到联系人头像Bitamp
                Bitmap contactPhoto = null;
                // photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
                if (photoid > 0) {
                    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactid);
                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
                    contactPhoto = BitmapFactory.decodeStream(input);
                }
                list.add(new Contacts(contactName, phoneNumber, contactPhoto));
            }
            phoneCursor.close();
        }
        //得到手机SIM卡联系人人信息
        Uri uri = Uri.parse("content://icc/adn");
        phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null, null);
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                // Sim卡中没有联系人头像
                Contacts contacts = new Contacts(contactName, phoneNumber, null);
                if (!list.contains(contacts)) {
                    list.add(contacts);
                }
            }
            phoneCursor.close();
        }
        return list;
    }


}
